import 'package:flutter/cupertino.dart';
import 'package:flutter_easyrefresh/easy_refresh.dart';
import 'package:flutter_smart_dialog/flutter_smart_dialog.dart';
import 'package:get/get.dart';
import 'package:xm_app/common/global/GlobalService.dart';
import 'package:xm_app/common/http/api_response.dart';
import 'package:xm_app/common/logger/LoggerUtil.dart';
import 'package:xm_app/common/utils/DeviceInfo.dart';
import 'package:xm_app/dao/VodDao.dart';
import 'package:xm_app/model/SearchData.dart';

class SearchController extends GetxController {
  final inputController = new TextEditingController();
  EasyRefreshController easyRefreshController = EasyRefreshController();
  SearchData searchData = SearchData();
  int showIndex = 0;
  int page = 1;
  String keyword = "";
  FocusNode focusNode = FocusNode();
  void onInit() {
    super.onInit();
    print("SearchController onInit");
    inputController.addListener(() {
      if (inputController.value.text != "") {
        update();
      }
    });
    focusNode.requestFocus();
  }

  search() {
    if (inputController.text.length == 0) {
      SmartDialog.showToast("请输入搜索内容");
      return;
    }
    focusNode.unfocus();
    page = 1;
    keyword = inputController.text;
    getData();
  }

  getData() async {
    ApiResponse res = await VodDao().search(keyword, page);
    if (res.status == Status.ERROR) {
      SmartDialog.showToast(res.exception.message);
      return;
    }
    searchData = res.data;
    showIndex = 1;
    update();
  }

  loadData() async {
    //默认每一页36条数据
    if (page >= (searchData.qty ?? 0 / 36.toDouble()).ceil()) {
      easyRefreshController.resetLoadState();
      easyRefreshController.finishLoad(noMore: true);
      return;
    }
    page++;
    ApiResponse res = await VodDao().search(keyword, page);
    if (res.status == Status.ERROR) {
      SmartDialog.showToast(res.exception.message);
      easyRefreshController.finishLoad(success: false);
      page--;
      return;
    }
    searchData.data.addAll(res.data.data);
    easyRefreshController.finishLoad(success: true);
    update();
  }

  cleanText() {
    inputController.text = "";
    update();
  }
}
